# coding=utf-8

"""
file description
"""


from pony.orm import Database, Required, Optional, db_session, select
from datetime import datetime, timedelta
from utils.loger import run_log
import hashlib
from uuid import uuid1
from project.setting import AUTH_SETTING


db = Database()


class User(db.Entity):
    """
    用户表
    """
    account = Required(str, 11, unique=True, index=True)  # 手机号、登录账号
    password = Required(str)
    create_time = Optional(datetime, default=lambda: datetime.now())

    token = Optional('AuthToken')

    @staticmethod
    def create_user(account, password, **kwargs):
        with db_session:
            m = hashlib.md5()
            m.update(password.encode("utf-8"))
            user = User(account=account, password=m.hexdigest(), **kwargs)
            run_log.info("create user succeed for account:%s" % account)
            return user

    def is_pwd_right(self, pwd):
        m = hashlib.md5()
        m.update(pwd.encode("utf-8"))
        return m.hexdigest() == self.password


class AuthToken(db.Entity):
    """
    用户认证Token表
    """
    token = Required(str, 36, unique=True, index=True)
    user = Optional(User)
    expire_time = Required(datetime)

    create_time = Required(datetime, default=lambda: datetime.now())

    @staticmethod
    @db_session
    def gen_token_for_user(user):
        token = str(uuid1())
        old_token = select(t for t in AuthToken if t.user == user).first()
        expire_time = datetime.now() + timedelta(minutes=AUTH_SETTING['token_age'])
        if old_token:
            old_token.token = token
            old_token.expire_time = expire_time
        else:
            AuthToken(token=token, user=user, expire_time=expire_time)
        run_log.info("gen token succeed for user:%s" % user.account)
        return token

